import { useEffect, useState } from "react"
import { Button, Form, Input, Modal, Select, message } from "antd"
import cnchar from "cnchar";
import { TextWidget, getMessage } from "@inbiz/react"
// import MultilingualInput from "@inbiz/basic/MultilingualInput";
import { addProcessForm } from "../server";

const AddModal = (props: any) => {
  const { visible, $visible, refresh, groupData, activeGroup, addGroup, design } = props
  // 保存loading
  const [saveLoading, $saveLoading] = useState<boolean>(false)
  // 保存并设计loading
  const [saveSetupLoading, $saveSetupLoading] = useState<boolean>(false)
  // 分组数据
  const [groupList, $groupList] = useState<any[]>([])
  const [form] = Form.useForm()

  useEffect(() => {
    visible && form.resetFields()
    activeGroup && form.setFieldsValue({ group: activeGroup })
  }, [visible])

  // 组合分组数据
  useEffect(() => {
    const list: any[] = []
    groupData.map((i: any) => {
      list.push(i)
      if (i.Children?.length) {
        i.Children.map((v: any) => {
          list.push({ ...v, down: true, ParentName: i.Name })
        })
      }
    })
    $groupList(list)
  }, [groupData])

  // 取消
  const cancel = () => {
    $visible(false)
  }

  // 保存
  const save = () => {
    savaData((type: boolean) => { $saveLoading(type) })?.then((res: any) => {
      message.success(getMessage('FormManage.save_succ'))
      $saveLoading(false)
      $visible(false)
      if (activeGroup == res.ParentId) refresh?.()
    })
  }

  // 保存并设计
  const saveAndSetup = () => {
    savaData((type: boolean) => { $saveSetupLoading(type) })?.then((res: any) => {
      message.success(getMessage('FormManage.save_succ'))
      $saveSetupLoading(false)
      $visible(false)
      if (activeGroup == res.ParentId) refresh?.()
      design?.(res)
    })
  }

  // 保存数据处理、接口调用
  const savaData = async (fn: any) => {
    const res = await form.validateFields()
    if (res) {
      fn?.(true)
      return new Promise((resolve, reject) => {
        addProcessForm({
          name: res.name?.trim?.(),
          description: res.remark,
          parentId: res.group,
          route: res.key,
          appId: props?.activeAppId
        }).then((res: any) => {
          if (res?.OutId) {
            resolve(res)
          } else {
            fn?.(false)
            reject()
          }
        })
      })
    }
    return
  }

  // 中文转拼音
  const cnTochare = (name: string) => {
    let route = cnchar.spell(getMessage(name)?.replaceAll(' ', '')) as string;
    route = route.toLowerCase();
    // @ts-ignore
    route = route.replaceAll('ü', 'v');
    return route
  }

  // 表单变化监听
  const onValuesChange = (info: any) => {
    if (info.name) {
      info.key = cnTochare(info.name)
      form.setFieldsValue(info);
    }
    if (info.key) {
      info.key = info.key.toLowerCase();
      form.setFieldsValue(info);
    }
  }

  return (
    <>
      <Modal
        title={getMessage('FormManage.add_form')} // 新建
        visible={visible}
        wrapClassName="form-manage-add-form-modal"
        onCancel={cancel}
        footer={[
          <Button onClick={cancel}>
            {/* 取消 */}
            <TextWidget>FormManage.cancelText</TextWidget>
          </Button>,
          <Button type='primary' onClick={saveAndSetup} loading={saveSetupLoading}>
            {/* 保存并设计 */}
            <TextWidget>FormManage.save_setup</TextWidget>
          </Button>,
          <Button type='primary' onClick={save} loading={saveLoading}>
            {/* 保存 */}
            <TextWidget>FormManage.save</TextWidget>
          </Button>
        ]}
      >
        <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 18 }} onValuesChange={onValuesChange}>
          {/* 所属分组 */}
          <Form.Item
            name='group'
            label={getMessage('FormManage.at_group')} // 所属分组
            rules={[{ required: true, message: getMessage('FormManage.at_group_quest') }]}
          >
            <Select
              dropdownClassName='form-manage-select-group'
              placeholder={getMessage('FormManage.please_sele')} // 请选择
              showSearch
              virtual={false}
              optionFilterProp="label"
              filterOption={(input, option) => {
                if (typeof option?.title == 'string') {
                  return (option?.title ?? '')?.toLowerCase().includes(input.toLowerCase())
                } else {
                  return false
                }
              }}
            >
              {
                groupList.map((item: any) => {
                  return (
                    <Select.Option
                      value={item.OutId}
                      key={item.OutId}
                      className={item.down ? 'form-group-down' : ''}
                      title={getMessage(item.Name)}
                    >
                      <TextWidget>{item.Name}</TextWidget>
                    </Select.Option>
                  )
                })
              }
            </Select>
          </Form.Item>
          {/* 表单名称 */}
          <Form.Item
            name='name'
            label={getMessage('FormManage.form_name')} // 表单名称
            required
            rules={[
              ({ }) => ({
                validator(_, value): any {
                  if (!value || value?.trim?.() == '') {
                    return Promise.reject(new Error(getMessage('FormManage.form_name_quest')))
                  } else if (value.length > 50) {
                    return Promise.reject(getMessage('FormManage.limit_group_length'))
                  } else if (/^[\u4E00-\u9FA5A-Za-z0-9\_\-\——\'\(\)\。\、\【\】\‘\’\“\”\《\》\……\（\）\s]+$/.test(value)) {
                    /* 暂时去掉对语言支持 */
                    // } else if (/^[\u4E00-\u9FA5A-Za-z0-9\_\-\——\'\(\)\。\、\【\】\‘\’\“\”\《\》\……\（\）\s]+$/.test(value.replace('.i18n', '').replace('{multilingual}', ''))) {
                    return Promise.resolve()
                  }
                  return Promise.reject(getMessage('FormManage.special_character'))
                },
              }),
            ]}
          >
            <Input
              placeholder={getMessage('FormManage.please_input')}
            />
            {/* 暂时去掉对语言支持 */}
            {/* <MultilingualInput
              placeholder={getMessage('FormManage.please_input')}
            /> */}
          </Form.Item>
          {/* 标识 */}
          <Form.Item
            name='key'
            label={getMessage('FormManage.key')}
            rules={[
              { required: true, message: getMessage('FormManage.key_quest') },
              {
                pattern: /^[a-zA-Z0-9_-]*$/,
                message: getMessage('FormManage.key_check'),
              },
              {
                pattern: /^.{2,50}$/,
                message: getMessage('FormManage.key_long'),
              }
            ]}
          >
            <Input placeholder={getMessage('FormManage.please_input')} />
          </Form.Item>
          {/* 描述 */}
          <Form.Item name='remark' label={getMessage('FormManage.form_remark')}>
            <Input.TextArea placeholder={getMessage('FormManage.please_input')} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

export default AddModal